package com.krui.iweibo.service.parseweibo;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.text.SpannableStringBuilder;

public class WeiboCallbackManager {
	
	private ConcurrentHashMap<String, List<WeiboParseCallback>> callbackMap;
	
	
	public WeiboCallbackManager() {
		
		callbackMap = new ConcurrentHashMap<String, List<WeiboParseCallback>>();
	}
	
	
	public void put(String weibo,WeiboParseCallback callback){
		
		if (!callbackMap.contains(weibo)) {
			callbackMap.put(weibo, new ArrayList<WeiboParseCallback>());
		}
		
		callbackMap.get(weibo).add(callback);
	}

	
	
	public void get(String weibo , SpannableStringBuilder spannable){

	
	}
	
	public boolean sendGetRequest(String path,Map<String , String > params,String encoding) throws MalformedURLException, IOException{
		//直接向请求地址附加参数
		StringBuilder sb = new StringBuilder(path);
		
		sb.append("?");
		
		if (params != null && !params.isEmpty()) {
			
			for(Map.Entry<String, String> entry : params.entrySet()){
				
				sb.append(entry.getKey()).append("=");
				//需要设定编码方式支持中文，TOMCAT服务器使用IOS-8859-1,服务器需要处理编码，这里也需要设置编码
				sb.append(URLEncoder.encode(entry.getValue(), encoding)).append("&");
			}
			//去掉最后一个多余的&
			sb.deleteCharAt(sb.toString().length() - 1);
			//建立连接
			HttpURLConnection urlConnection = (HttpURLConnection)new URL(sb.toString()).openConnection();
			//需要大写
			urlConnection.setRequestMethod("GET");
			//设置请求超时时间
			urlConnection.setReadTimeout(5 * 1000);
			//判断是否请求正确，必须，因为可能请求到的是错误页面
			if (urlConnection.getResponseCode() == 200) {
				
				return true;
			}
		}
		return false;
	}
	
	
}
